<style>
.box {
  margin-top: 250px;
  margin-left: 1000px;
}
</style>
<template>
  <div class="box">
    <el-form
      ref="ruleFormRef"
      style="max-width: 350px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" placeholder="输入账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" placeholder="输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="denglu"> 登录 </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import router from '@/router'
import { useCounterStore } from '@/stores/user'

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  username: '',
  password: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, message: '账号不为空' }],
  password: [{ required: true, message: '密码不为空' }],
})

const denglu = () => {
  ruleFormRef.value?.validate().then(async () => {
    const res = await axios.post('/api/login', ruleForm)
    console.log(res)
    const { code, data, message } = res.data
    console.log(code, data, message)
    if (code === 10000) {
      alert(message)
      router.push('/home')
      const token = data.accessToken
      // // console.log(token)
      const yhzx = await getInfo(token)
      //   console.log(yhzx)
      const { code: code1, data: data1, message: message1 } = yhzx.data
      console.log(code1, data1, message1)

      //存仓库
      const store = useCounterStore()
      store.setUser(data1)
    } else {
      alert(message)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
